<template>
    <div>
        <div class="font-20 mar-x-20 mar-t-20">个人资料</div>
		<Lines h="1px" w="100%" bg="#E6E8EB" class="mar-t-20" />
        <div class="pad-10 text-nowrap">
            <div class="flex align-center mar-t-20">
                <div class="pos-r">
                    <el-upload
                        ref="uploadFile"
                        :action="upload.action"
                        :name="upload.name"
                        :accept="upload.accept"
                        :limit="upload.limit"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :on-success="handleFileSuccess"
                        :on-error="handleFileError"
                        :on-progress="handleFileProgress"
                    >
                        <template slot="trigger">
                            <div class="avatar-wrapper">
                                <img :src="getAvatar" class="avatar-image" />
                                <div class="mask">
                                    <i class="el-icon-circle-plus-outline"></i>
                                    <span class="font-12 mar-t-5">点击修改头像</span>
                                </div>
                            </div>
                        </template>
                    </el-upload>
                </div>

                <div class="mar-l-20">
                    <div class="font-14 mar-t-15">上传头像</div>
                    <div class="color-8a919f font-12 mar-t-15 text-wrap">
                        <div>格式：支持JPG、PNG、JPEG、GIF、BMP（推荐：100*100 像素）</div>
                        <div>大小：5M以内</div>
                    </div>
                </div>
            </div>

            <div class="color-252933 font-14 mar-t-30">
                <div class="flex gap-10 justify-center align-center w-90">
                    <span>性别</span>
                    <div class="w-80">
                        <el-radio v-model="radio" :label="0">男</el-radio>
                        <el-radio v-model="radio" :label="1">女</el-radio>
                    </div>
                </div>

                <div>
                    <CustomInput
                        v-model="username"
                        label="账号"
                        placeholder="请输入账号"
                        :maxlength="20"
                    />
                </div>

                <div>
                    <CustomInput
                        v-model="nickName"
                        label="昵称"
                        placeholder="请填写昵称"
                        :maxlength="20" 
                    />
                </div>

                <div>
                    <CustomInput
                        v-model="job"
                        label="职位"
                        placeholder="请填写职位"
                        :maxlength="20" 
                    />
                </div>

                <div>
                    <CustomInput
                        v-model="email"
                        label="邮箱"
                        placeholder="请填写邮箱"
                        :maxlength="50"
                    />
                </div>

                <div>
                    <CustomInput
                        v-model="companyName"
                        label="公司"
                        placeholder="请填写公司名称"
                        :maxlength="50" 
                    />
                </div>

                <div>
                    <CustomInput
                        v-model="introduction"
                        type="textarea"
                        label="简介"
                        placeholder="请填写个人介绍，兴趣爱好等"
                        :maxlength="200" 
                    />
                </div>
            </div>

            <div class="flex justify-center pad-y-20">
                <el-button type="primary" size="small" @click="handleSaveData()">保存修改</el-button>
            </div>
        </div>
    </div>
</template>

<script>
    import Lines from '@/components/Lines/index'
    import Utils from '@/utils/utils'
    import CustomInput from '@/components/CenterPersonal/CustomInput'

    import { mapState } from 'vuex'
    import { updateUserInfo } from '@/apis/user'

    export default {
        props: {
        },

        components: {
            Lines,
            CustomInput,
        },

        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo,
                token: state => state.user.token,
                defaultAvatar: state => state.user.defaultAvatar, // 默认头像
            }),

            // 上传头像请求头
            uploadHeaders() {
                return {
                    'Authorization': 'Bearer ' + this.token
                }
            },

            // 获取头像
            getAvatar() {
                return this.upload.fileList.length > 0 ? process.env.VUE_APP_IMG_BASE_API + this.upload.fileList[0].url : this.defaultAvatar
            }
        },

        data() {
            return {
                radio: 0, // 性别二选一
                pageLoading: false, // 页面加载中
                username: '', // 账号
                job: '', // 职位
                nickName: '', // 昵称
                companyName: '', // 公司名称
                introduction: '', // 介绍
                email: '', // 邮箱

                // 上传
                upload: {
                    action: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PROD_UPLOAD_BASE_API : process.env.VUE_APP_PROD_UPLOAD_BASE_API,
                    name: 'file',
                    accept: '.jpg,.png,.jpeg,.gif,.bmp',
                    limit: 1,
                    fileList: [],
                },
            }
        },

        mounted() {
            this.showUserInfo()
        },

        methods: {
            // 显示用户信息
            showUserInfo() {
                this.username = this.userInfo.username
                this.nickName = this.userInfo.nickName
                this.job = this.userInfo.job
                this.email = this.userInfo.email
                this.companyName = this.userInfo.companyName
                this.introduction = this.userInfo.introduction
                this.radio = this.userInfo.sex

                if (this.userInfo.avatar) {
                    this.upload.fileList.push({
                        url: this.userInfo.avatar,
                    })
                }
            },

            // 保存表单数据
            handleSaveData() {
                let params = {
                    username: this.username,
                    nickName: this.nickName,
                    job: this.job,
                    email: this.email,
                    companyName: this.companyName,
                    introduction: this.introduction,
                    sex: this.radio,
                    avatar: this.upload.fileList.length > 0 ? this.upload.fileList[0].url : ''
                }

                this.pageLoading = Utils.loading('保存中...')

                updateUserInfo(params).then(res => {
                    this.pageLoading.close()

                    if (res.code === 200) {
                        Utils.popUpMsg('success', '个人资料修改成功！', 1500)
                        this.$store.dispatch('user/getUserInfo', res.data)
                    } else {
                        Utils.popUpMsg('error', res.msg, 3000)
                    }
                }).catch(error => {
                    this.pageLoading.close()
                })
            },

            // 文件上传成功
            handleFileSuccess(response, file) {
                this.upload.fileList = []
                this.pageLoading.close()

                if (response.code === 200) {
                    this.upload.fileList.push(response.data)
                    Utils.popUpMsg('success', response.msg, 1500)
                } else {
                    Utils.popUpMsg('error', response.msg, 3000)
                }

                this.$refs.uploadFile.clearFiles()
            },

            // 文件上传错误
            handleFileError(error, file) {
                this.pageLoading.close()
                this.$refs.uploadFile.clearFiles()
            },

            // 文件上传时
            handleFileProgress(event,file) {
                this.pageLoading = Utils.loading('头像上传中...')
            },

            // 账号输入框内容回调
            accountChange(e) {
                let accountText = e.target.value
                let accountLength = accountText.length

                if (accountLength > 20) {
                    this.account = accountText.substring(0, 20)
                } else {
                    this.account = accountText
                }

                this.accountCount = accountLength
            },

            // 职位输入框内容回调
            jobChange(e) {
                let jobText = e.target.value
                let jobLength = jobText.length

                if (jobLength > 50) {
                    this.job = jobText.substring(0, 50)
                } else {
                    this.job = jobText
                }

                this.jobCount = jobLength
            },

            // 邮箱输入框内容回调
            emailChange(e) { 
                let emailText = e.target.value
                let emailLength = emailText.length

                if (emailLength > 50) { 
                    this.email = emailText.substring(0, 50)
                } else { 
                    this.email = emailText
                }

                this.emailCount = emailLength
            },

            // 公司输入框内容回调
            companyChange(e) { 
                let companyText = e.target.value
                let companyLength = companyText.length

                if (companyLength > 50) { 
                    this.company = companyText.substring(0, 50)
                } else { 
                    this.company = companyText
                }

                this.companyCount = companyLength
            },

            // 个人介绍输入框内容回调
            introduceChange(e) {
                let introduceText = e.target.value
                let introduceLength = introduceText.length

                if (introduceLength > 100) { 
                    this.introduce = introduceText.substring(0, 100)
                } else { 
                    this.introduce = introduceText
                }

                this.introduceCount = introduceLength
            }
        },
    }
</script>

<style lang="scss" scoped>
   .avatar-wrapper {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        cursor: pointer;
        overflow: hidden;
        position: relative;
        transition: border-color 0.3s;
    }

    .avatar-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        flex-shrink: 0;
        display: block;
    }

    .mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        color: white;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: opacity 0.3s;
    }

    .avatar-wrapper:hover .mask {
        opacity: 1;
    }

    .mask i {
        font-size: 26px;
    }
</style>
